package postpc.powerreminders.com.ui.activities;

import postpc.powerreminders.com.db.RotgDatabase;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class ReminderEditActivity extends Activity {
	
	
	
	private long m_ID;
	private long m_LocationID;
	private int m_Action;
	
	private String m_PhoneNumber;
	
	private static final int PICK_CONTACT = 5; // Why 5? because I feel like it
	private static final String TAG = "ReminderEditActivity";
	
	private void fillData() {
		Spinner locationsSpinner = (Spinner)findViewById(postpc.powerreminders.com.R.id.reminder_edit_location);
		RotgDatabase db = RotgDatabase.getInstance();
		
		Cursor allLocations = db.fetchAllLocations();
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				getApplicationContext(), android.R.layout.simple_spinner_item, 
				allLocations, 
				new String[] { RotgDatabase.NAME },
				new int[] { android.R.id.text1 } );
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		locationsSpinner.setAdapter(adapter);
		
		
		if (m_ID >= 0) {
			Log.d(TAG, "Showing reminder edit screen for id="+m_ID);
			
			Cursor reminder = db.fetchReminder(m_ID);
			
			EditText nameText = (EditText)findViewById(postpc.powerreminders.com.R.id.reminder_edit_name);
			EditText messageText = (EditText)findViewById(postpc.powerreminders.com.R.id.reminder_edit_message);
			
			nameText.setText(reminder.getString(reminder.getColumnIndexOrThrow(RotgDatabase.NAME)));
			messageText.setText(reminder.getString(reminder.getColumnIndexOrThrow(RotgDatabase.MESSAGE)));
			
			int locationId = reminder.getInt(reminder.getColumnIndexOrThrow(RotgDatabase.LOCATION_ID));
			
			int pos = 0;
			allLocations.moveToFirst();
			
			if (allLocations.getCount() > 0) {
				do {
					if (allLocations.getInt(allLocations.getColumnIndexOrThrow("_id")) == locationId) {
						Log.d(TAG, "Found position for spinnner: " + pos);
						break;
					}
					++pos;
				}
				while(allLocations.moveToNext());
				
				if (pos < allLocations.getCount())
					locationsSpinner.setSelection(pos);
			}
			
			m_Action = reminder.getInt(reminder.getColumnIndexOrThrow(RotgDatabase.ROTG_ACTION));
			Log.d(TAG, "Setting m_Action = " + m_Action);
			switch (m_Action) {
			case RotgDatabase.ACTION_LOCATION:
				RadioButton locationRadio = (RadioButton)findViewById(postpc.powerreminders.com.R.id.reminder_edit_radio_location);
				locationRadio.setChecked(true);
				break;
			case RotgDatabase.ACTION_PHONE:
				RadioButton phoneRadio = (RadioButton)findViewById(postpc.powerreminders.com.R.id.reminder_edit_radio_phone);
				phoneRadio.setChecked(true);
				break;
			case RotgDatabase.ACTION_APP:
				RadioButton appRadio = (RadioButton)findViewById(postpc.powerreminders.com.R.id.reminder_edit_radio_app);
				appRadio.setChecked(true);
				break;
			}
			
			m_PhoneNumber = reminder.getString(reminder.getColumnIndexOrThrow(RotgDatabase.PHONE_NUMBER));
			// TODO: set the contact's name in the ui somehow, instead of his phone number
			TextView contactView = (TextView)findViewById(postpc.powerreminders.com.R.id.reminder_edit_contact_name);
	        contactView.setText(m_PhoneNumber);
	        
	        String appId = reminder.getString(reminder.getColumnIndexOrThrow(RotgDatabase.APPLICATION));
	        Spinner appSpinner = (Spinner)findViewById(postpc.powerreminders.com.R.id.reminder_edit_app_spinner);
	        
	        int index;
	        String[] appIds = getResources().getStringArray(postpc.powerreminders.com.R.array.app_ids); 
	        for (index = 0; index < appIds.length; ++index) {
	        	if (appIds[index].equals(appId)) {
	        		break;
	        	}
	        }
	        
	        if (index < appIds.length) {
	        	appSpinner.setSelection(index);
	        }
	        
		}
		
		
		db.close();
	}
	
	private void saveReminder() {
		
		EditText nameText = (EditText)findViewById(postpc.powerreminders.com.R.id.reminder_edit_name);
		EditText messageText = (EditText)findViewById(postpc.powerreminders.com.R.id.reminder_edit_message);

		String name = nameText.getText().toString();
		String message = messageText.getText().toString();
		
		Spinner appSpinner = (Spinner)findViewById(postpc.powerreminders.com.R.id.reminder_edit_app_spinner);
		String appId = getResources().getStringArray(postpc.powerreminders.com.R.array.app_ids)[appSpinner.getSelectedItemPosition()];

		RotgDatabase db = RotgDatabase.getInstance();
		if (m_ID >= 0) {
			db.updateReminder(m_ID, m_LocationID, name, message, appId, m_PhoneNumber, RotgDatabase.REMINDER_ACTIVE, m_Action);
			db.printDataBase();
		}
		else {
			db.newReminder(m_LocationID, name, message, appId, m_PhoneNumber, RotgDatabase.REMINDER_ACTIVE, m_Action);
		}
		db.close();

		setResult(RESULT_OK);
		finish();
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(postpc.powerreminders.com.R.layout.reminder_edit);
		
		RadioGroup radioGroup = (RadioGroup)findViewById(postpc.powerreminders.com.R.id.reminder_edit_radio);
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				Log.d(TAG, "RadioGroup checked changed. checkedId = " + checkedId);
				
				View viewToShow = null;
				View locationView = findViewById(postpc.powerreminders.com.R.id.reminder_edit_location_group);
				View phoneView = findViewById(postpc.powerreminders.com.R.id.reminder_edit_phone_group);
				View appView = findViewById(postpc.powerreminders.com.R.id.reminder_edit_app_group);
				
				if (checkedId == postpc.powerreminders.com.R.id.reminder_edit_radio_location) {
					viewToShow = locationView;
					m_Action = RotgDatabase.ACTION_LOCATION;
				}
				else if (checkedId == postpc.powerreminders.com.R.id.reminder_edit_radio_phone) {
					viewToShow = phoneView;
					m_Action = RotgDatabase.ACTION_PHONE;
				}
				else if (checkedId == postpc.powerreminders.com.R.id.reminder_edit_radio_app) {
					viewToShow = appView;
					m_Action = RotgDatabase.ACTION_APP;
				}
				
				locationView.setVisibility(View.GONE);
				phoneView.setVisibility(View.GONE);
				appView.setVisibility(View.GONE);
				
				viewToShow.setVisibility(View.VISIBLE);
			}
		});
		
		Spinner spinner = (Spinner) findViewById(postpc.powerreminders.com.R.id.reminder_edit_app_spinner);
	    ArrayAdapter<CharSequence> appNamesAdapter = ArrayAdapter.createFromResource(
	            this, postpc.powerreminders.com.R.array.app_names, android.R.layout.simple_spinner_item);
	    appNamesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(appNamesAdapter);
		
		m_ID = getIntent().getLongExtra("id", -1);
		fillData();
		
		Button saveButton = (Button)findViewById(postpc.powerreminders.com.R.id.reminder_edit_save_button);
		saveButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				saveReminder();
			}
		});
		
		Spinner locationsSpinner = (Spinner)findViewById(postpc.powerreminders.com.R.id.reminder_edit_location);
		locationsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, 
					int position, long id) {
				m_LocationID = id;
				Log.i(TAG, "Setting m_LocationID = " + id);
				
			}
			
			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				m_LocationID = -1; 
			}
		});
		
		
		
		Button contactButton = (Button)findViewById(postpc.powerreminders.com.R.id.reminder_edit_contact_button);
		contactButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, PICK_CONTACT);
			}
		});
	}
	
	// Android sucks, this UGLY UGLY code is meant to extract the contact info from the intent we just got.
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_CONTACT) {
			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				
				if (c.moveToFirst()) {
				    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
					boolean hasPhone = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER)).equals("1");
					
					if (hasPhone) {
						Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
				        if (phones.moveToNext()) 
				        {
				          m_PhoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				          m_PhoneNumber = m_PhoneNumber.replaceAll("[^0-9]", ""); // gets rid of non-numbers
				          Log.d(TAG, "Setting m_PhoneNumber=" + m_PhoneNumber);
				          TextView contactView = (TextView)findViewById(postpc.powerreminders.com.R.id.reminder_edit_contact_name);
				          String contactName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				          Log.i(TAG, "Got contact name = " + contactName);
				          contactView.setText(contactName);
				        }
					}
				}
			}
		}
	}

	
}
